﻿using CQRSFramework.Common.Serializer;
using CQRSFramework.Infrustructures;
using CQRSFramework.Messages;
using CQRSFramework.RabbitMQ;
using System;
using System.Threading.Tasks;

namespace CQRSFramework.Commands
{
    public class CommandBus : ICommandBus
    {
        private readonly IMessagePublisher _messagePublisher;
        private readonly IJsonSerializer _jsonSerializer;
        private readonly IRoutingKeyProvider<ICommand> _routingKeyProvider;
        private readonly ITypeNameProvider _typeNameProvider;
        public CommandBus(IMessagePublisher messagePublisher, IJsonSerializer jsonSerializer, IRoutingKeyProvider<ICommand> routingKeyProvider, ITypeNameProvider typeNameProvider)
        {
            _messagePublisher = messagePublisher;
            _jsonSerializer = jsonSerializer;
            _routingKeyProvider = routingKeyProvider;
            _typeNameProvider = typeNameProvider;
        }
        public void Publish(ICommand command)
        {
            var message = BuildQueueMessage(command);
            _messagePublisher.Publish(message, "", _routingKeyProvider.GetRoutingKey(command));
        }
        public Task PublishAsync(ICommand command)
        {
            throw new NotImplementedException();
        }
        private QueueMessage BuildQueueMessage(ICommand command)
        {
            var queueMessage = new QueueMessage
            {
                TypeName = _typeNameProvider.GetTypeName(command.GetType()),
                Body = _jsonSerializer.Serialize(command)
            };
            return queueMessage;
        }
    }
}
